<?php
include('inc.php');

$IsUser=isset($_GET['id']);
$IsAdmin=isset($_GET['hash']);
$HasAction=isset($_GET['action']);
$SaveEditForm=isset($_GET['save']);

if($SaveEditForm)
{
	$Status='2';
	$Message="未找到表单，请先新建一个表单\r\n再次尝试保存?";	
	if(isset($_SESSION['id']))
	{
		$id=$_SESSION['id'];
		$data=$_POST['data'];
		
		$FormFileName=GetFormFileName($id);
		$DataFileName=GetDataFileName($id);
		if($GLOBALS['S']->fileExists(StorageDomain,$FormFileName))
			$GLOBALS['S']->delete(StorageDomain,$FormFileName);
		if($GLOBALS['S']->fileExists(StorageDomain,$DataFileName))
			$GLOBALS['S']->delete(StorageDomain,$DataFileName);
			
		$GLOBALS['S']->write(StorageDomain,$FormFileName,$data);	die($data);
		$GLOBALS['S']->write(StorageDomain,$DataFileName,'Empty');	
		$Status='1';
		$Message='ok';
	}
	die(json_encode(array('Status'=>$Status,'Message'=>$Message,'LastModifiedTime'=>0)));
}
elseif($HasAction)
{
	$action=$_GET['action'];
	switch($action)
	{
		case 'create':
			$_SESSION['id']=mktime();
			ShowFormEditor($_SESSION['id'],'');
			break;
		case 'cancel':
			$id=$_SESSION['id'];
			$f1=GetFormFileName($id);
			$f2=GetDataFileName($id);
			if($GLOBALS['S']->fileExists(StorageDomain,$f1))
				$GLOBALS['S']->delete(StorageDomain,$f1);
			if($GLOBALS['S']->fileExists(StorageDomain,$f2))
				$GLOBALS['S']->delete(StorageDomain,$f2);
			session_destroy();
			header('Location:./');			
			break;
		case 'edit':
			if(isset($_GET['id'])&&isset($_GET['hash'])&&$_GET['hash']==GetPwd($_GET['id']))			
			{
				ShowFormEditor($_GET['id'],$_GET['hash']);
			}
			break;
	}
}
elseif($IsUser)
	ShowForm($_GET['id']);
elseif($IsAdmin)
{
	ShowDataReport($_GET['hash']);
}
else
	{
	echo file_get_contents('html/instruction.html');
}
?>